<?php

namespace App\Http\Controllers\Api;

use App\Http\ApiResponse;
use App\Models\VideoCategory;
use App\Models\VideoData;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Log;

/**
 * 视频相关
 * Class VideoController
 * @package App\Http\Controllers\Api
 */
class VideoController extends Controller
{
    use ApiResponse;

    const perPage = 8;


    //获取视频列表
    public function getVideoLists(Request $request)
    {
        $params = [
            'chanel' => $request->get('chanel'),
            'option' => $request->get('option'),
        ];
        $lists=VideoData::select('id','title','thumb','time','view_num','video_link','cate_id')
            ->where(function($query) use($params){
                if ($params['chanel']){
                    $query->where('chanel',$params['chanel']);
                }
                if ($params['option']){
                    $query->where('is_option',1);
                }
                $query->where('status',VideoData::STATUS_YES);
            })
            ->with(['category' => function ($query) {
                $query->select('id', 'title','avatar')->get();
            }])
            ->orderBy('sort','DESC')
            ->paginate(10);
        return $this->respSuccess('success',$lists);
    }
    //获取视频详情
    public function getVideoInfo(Request $request)
    {
        $id=$request->get('id');
        if (empty($id)){
            return $this->respError('参数错误');
        }
        $info = VideoData::where('status',VideoData::STATUS_YES)
            ->select('id','title','thumb','time','view_num','old_video_link','cate_id')
            ->with(['category' => function ($query) {
                $query->select('id', 'title','avatar')->get();
            }])
            ->find($id);
        if(!$info){
            return $this->respError('数据信息不存在');
        }
        $video = $this->getVideo($info['old_video_link']);
        $info['video_link'] = $video;
        $info->increment('view_num');
        return $this->respSuccess('success',$info);
    }


    protected function getVideo($url){
        //获取腾讯视频真实地址
        if (strstr($url, 'v.qq.com')) {
            //匹配腾讯链接拿到所需的vid
            $result = preg_match_all('/\/([0-9a-zA-Z]+).html/', $url, $matchs);
            if ($result) {
                $matchs = array_flatten($matchs);
            }
            $vid = $matchs[1] ?? '';
            $murl = 'http://vv.video.qq.com/getinfo?vids=' . $vid . '&platform=101001&charge=0&otype=json';
            $res = $this->httpsRequest($murl);
            $res = str_replace('QZOutputJson=', '', $res);
            $res = rtrim($res, ";");
            $res = json_decode($res, true);
            $url = $res['vl']['vi'][0]['ul']['ui'][0]['url'];
            $fn = $res['vl']['vi'][0]['fn'];
            $fvkey = $res['vl']['vi'][0]['fvkey'];
            return $url . $fn . '?vkey=' . $fvkey;
        }

    }

    function httpsRequest($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }




    //获取视频详情列表
    public function getVideoInfoList(Request $request)
    {
        $id=$request->get('id');
        if (empty($id)){
            return $this->respError('参数错误');
        }
        $rand = rand(1, 30);
        $lists=VideoData::select('id','title','thumb','time','view_num','video_link','cate_id')
            ->where('id','<>', $id)
            ->where('rand_cate', $rand)
            ->where('status',VideoData::STATUS_YES)
            ->with(['category' => function ($query) {
                $query->select('id', 'title','avatar')->get();
            }])
            ->orderBy('sort','DESC')
            ->paginate(20);
        return $this->respSuccess('success',$lists);
    }

    //获取视频分类
    public function getVideoCategory(Request $request)
    {
        //获取分类信息
        //统计分类下视频总人气
        //统计分类下视频总个数
        //获取分类下所有视频
        $id=$request->get('id');
        $info = VideoCategory::where('status',VideoCategory::STATUS_YES)
            ->find($id);
        $nums = VideoData::where('cate_id',$id)->select(\DB::raw('sum(view_num) as view_num'),
            \DB::raw('count(id) as nums'))
            ->first();
        $info['nums'] = $nums;
        return $this->respSuccess('success',$info);
    }

    //获取视频分类
    public function getVideoCategoryList(Request $request)
    {
        $id=$request->get('id');
        $lists=VideoData::where('cate_id',$id)
            ->select('id','title','thumb','time','view_num','video_link','cate_id')
            ->where('status',VideoData::STATUS_YES)
            ->with(['category' => function ($query) {
                $query->select('id', 'title','avatar')->get();
            }])
            ->orderBy('sort','DESC')
            ->paginate(20);
        return $this->respSuccess('success',$lists);
    }

    public function getVideoCategoryGood(){
        $lists=VideoData::where('is_option',1)
            ->select('id','title','thumb','time','view_num','video_link','cate_id','chanel')
            ->where('status',VideoData::STATUS_YES)
            ->get()
            ->groupBy('chanel');
        $_lists = [];
        foreach ($lists as $key=>$list){
            if(count($list)>2){
                $_lists[$key][] = $list[0];
                $_lists[$key][] = $list[1];
            }else{
                $_lists[$key] = $list;
            }
        }
        return $this->respSuccess('success',$_lists);
    }

}
